package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.fragments.WillingApperenceFragment;
import com.pocketsweet.ui.fragments.WillingHotFragment;
import com.pocketsweet.ui.fragments.WillingMoodFragment;
import com.pocketsweet.ui.fragments.WillingSpecificFragment;
import com.pocketsweet.ui.fragments.WillingVoiceFragment;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.OnTabSelectedListener;
import com.pocketsweet.ui.uilib.SimpleViewPagerIndicator;
import com.pocketsweet.ui.uilib.TagLayout;
import com.pocketsweet.ui.uilib.TagView;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.SimpleViewPagerIndicator.onTextClickListener;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_edit_like)
public class EditWilling extends BaseActivity implements OnClickListener,
		OnTabSelectedListener {
	private HeaderLayout header;
	private MLUser mlUser = new MLUser();
	private SimpleViewPagerIndicator mIndicator;
	private ViewPager mViewPager;
	private List<Fragment> listViews;
	private FragmentPagerAdapter mAdapter;
	public String tab;
	private String[] mTitles = new String[] { "热门", "情感", "个性", "声音", "外貌" };
	public ArrayList<String> willingList = new ArrayList<String>();// 将值传给编辑页面，编辑页面不用再请求网络
	private ArrayList<String> willingRemoveList = new ArrayList<String>();// 将值传给编辑页面，编辑页面不用再请求网络

	@ViewInject(R.id.edtLike)
	private static EditText edtLike;

	@ViewInject(R.id.tagLike)
	private TagLayout tagLike;

	@ViewInject(R.id.btnAdd)
	private TextView btnAdd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mlUser = UserService.getCurrentUser();
		initView();
		initPaperView();
		initTag();
		setHeaderFunction();
	}

	private void initView() {
		if (mlUser.getWillingTags() != null && mlUser.getWillingTags().size() > 0) {
			for (String like : mlUser.getWillingTags()) {
				addLabel(like);
			}
		}
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edtLike.getWindowToken(), 0);
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setMiddleText("我希望你");
		header.setRightText("");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				saveLike();
				EditWilling.this.finish();
			}
		});
	}

	private void initPaperView() {
		mIndicator = (SimpleViewPagerIndicator) findViewById(R.id.id_stickynavlayout_indicator);
		mViewPager = (ViewPager) findViewById(R.id.id_stickynavlayout_viewpager);
		mIndicator.setTitles(mTitles);
		mIndicator.setOnTextClickListener(new onTextClickListener() {
			@Override
			public void onTextClick(View v, int position) {
				mViewPager.setCurrentItem(position);

			}
		});
		listViews = new ArrayList<Fragment>();
		listViews.add(new WillingHotFragment());
		listViews.add(new WillingMoodFragment());
		listViews.add(new WillingSpecificFragment());
		listViews.add(new WillingVoiceFragment());
		listViews.add(new WillingApperenceFragment());
		mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
			@Override
			public int getCount() {
				return mTitles.length;
			}

			@Override
			public Fragment getItem(int position) {
				return listViews.get(position);
			}

		};

		mViewPager.setAdapter(mAdapter);
		mViewPager.setCurrentItem(0);

		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				mIndicator.scroll(position);
			}

			@Override
			public void onPageScrolled(int position, float positionOffset,
					int positionOffsetPixels) {
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});
	}

	private void initTag() {
		tagLike.setLimitCount(8);
		btnAdd.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 获取输入文字
				String label = edtLike.getText().toString();
				// 非有效标签直接返回
				if (TextUtils.isEmpty(label.trim())) {
					return;
				} else {
					// 有效标签，添加
					String temp;
					for (int i = 0; i < willingList.size(); i++) {
						temp = willingList.get(i);
						if (temp.equals(label)) {
							ToolKits.toast(EditWilling.this, "已添加过");
							return;
						}
					}
					addLabel(label);
					mlUser.setWillingTags(willingList);
				}
			}
		});

	}

	/** 
     * 计算分享内容的字数，一个汉字=两个英文字母，一个中文标点=两个英文标点 注意：该函数的不适用于对单个字符进行计算，因为单个字符四舍五入后都是1 
     *  
     * @param c 
     * @return 
     */  
    private long calculateLength(CharSequence c) {  
        double len = 0;  
        for (int i = 0; i < c.length(); i++) {  
            int tmp = (int) c.charAt(i);  
            if (tmp > 0 && tmp < 127) {  
                len += 0.5;  
            } else {  
                len++;  
            }  
        }  
        return Math.round(len);  
    }  

	protected void addLabel(final String label) {
		if (calculateLength(label) > 6) {
			ToolKits.toast(EditWilling.this, "超出字数限制");
			return;
		}
		if (tagLike.container.size() >= 8) {
			ToolKits.toast(EditWilling.this, "您已经添加了8个标签了");
			return;
		}
		willingList.add(label);
		final TagView item = new TagView(EditWilling.this);
		item.setName(label);
		item.getDelet().setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 移除标签
				Animation anim = AnimationUtils.loadAnimation(EditWilling.this,
						R.anim.unzoom_out);
				anim.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {

					}

					@Override
					public void onAnimationRepeat(Animation animation) {

					}

					@Override
					public void onAnimationEnd(Animation animation) {
						tagLike.removeView(item.getTag().toString());
						String temp;
						for (int i = 0; i < willingList.size(); i++) {
							temp = willingList.get(i);
							if (temp.equals(label)) {
								willingList.remove(i);
								willingRemoveList.add(label);
								mlUser.removeWillingTags(willingRemoveList);
								break;
							}
						}
					}
				});
				item.startAnimation(anim);

			}
		});
		tagLike.addView(item);
		edtLike.setText("");
	}

	public void saveLike() {
		mlUser.saveInBackground(new SaveCallback() {
			@Override
			public void done(AVException arg0) {
				// TODO Auto-generated method stub
				if (arg0 == null) {
					edtLike.setText("");
				} else {
//					Log.e("==error", "添加喜欢失败" + arg0.getMessage());
				}
			}
		});
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTabSelected(String tab) {
		String temp;
		for (int i = 0; i < willingList.size(); i++) {
			temp = willingList.get(i);
			if (temp.equals(tab)) {
				return;
			}
		}
		addLabel(tab);
		mlUser.setWillingTags(willingList);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 此处写处理的事件
			saveLike();
			EditWilling.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}
}
